﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;

namespace Torrenter.Common.Objects
{
    [Serializable]
    public class Show
    {
        public bool AddSeason(ShowSeason season)
        {
            if (Seasons.Any(s=>s.SeasonNumber==season.SeasonNumber))
            {
                return false;
            }
            Seasons.Add(season);
            return true;
        }


        

        public Torrent GetNextEpisode()
        {
            foreach (var season in Seasons.OrderBy(s => s.SeasonNumber))
            {
                if (season.Episondes.Last().WasFound)
                {
                    continue;
                }
                var torrent =
                    season.Episondes.OrderBy(ep => ep.EpisodeDefinition.EpisodeNumnber).
                        FirstOrDefault(t=>!t.WasFound);
                if (torrent != null)
                {
                    return torrent;
                }
            }
            return null;
        }

        public Show()
        {
            Seasons = new List<ShowSeason>();
        }

        #region public properties
        public List<ShowSeason> Seasons { get; set; }

        /// <summary>
        /// the name of the season
        /// </summary>
        public string ShowName { get; set; }

        [XmlIgnore]
        public Torrent LastEpisodeFound
        {
            get
            {                
                foreach (var season in Seasons.OrderBy(s => s.SeasonNumber))
                {
                    if (season.Episondes.Last().WasFound)
                    {
                        continue;
                    }
                    var torrent =
                        season.Episondes.OrderBy(ep => ep.EpisodeDefinition.EpisodeNumnber).
                            LastOrDefault(t => t.WasFound);
                    if (torrent != null)
                    {
                        return torrent;
                    }
                }
                var tt = (Seasons.OrderBy(s => s.SeasonNumber).LastOrDefault(s => s.Episondes.Last().WasFound));
                if (tt!=null)
                {
                    return tt.Episondes.Last();
                }
                return null;
            }
        }

        [XmlIgnore]
        public Torrent NextEpisode
        {
            get { return GetNextEpisode(); }
        }

        public override string ToString()
        {
            return this.ShowName;
        }

        #endregion

        
    }
}
